package org.liziing.shortlink.project.mq.idempotent;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 消息队列幂等消息处理器
 */

@Component
@RequiredArgsConstructor
public class MessageQueueIdempotentHandler {

    private final StringRedisTemplate stringRedisTemplate;
    private static final String IDEMPOTENT_REDIS_KEY = "short-link:idempotent:";

    /**
     * 设置幂等消息缓存
     * @param id 消息队列 id
     * @return 返回是否设置成功
     */
    public Boolean idempotentMessageQueue(String id) {
        String key = IDEMPOTENT_REDIS_KEY + id;
        return Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(key, "0", 2, TimeUnit.MINUTES));
    }

    /**
     * 判断当前消息是否消费完成
     * @param id 队列id
     * @return  返回判断是否成功
     */
    public Boolean hasAccomplish(String id) {
        String key = IDEMPOTENT_REDIS_KEY + id;
        return Objects.equals(stringRedisTemplate.opsForValue().get(key), "1");
    }

    /**
     * 设置流程消费成功
     * @param id 消息id
     */
    public void setAccomplish(String id) {
        String key = IDEMPOTENT_REDIS_KEY + id;
        if (Objects.equals(stringRedisTemplate.opsForValue().get(key), "0")) {
            stringRedisTemplate.opsForValue().set(key, "1", 2, TimeUnit.MINUTES);
        }
    }
    /**
     * 删除幂等消息队列缓存
     * @param id 消息队列 id
     */
    public void delIdempotentMessageQueue(String id) {
        String key = IDEMPOTENT_REDIS_KEY + id;
        stringRedisTemplate.delete(key);
    }
}
